package com.young.context;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public final class Profile {

    private static final String SEPARATOR = "@";

    private static final Map<String, String> SM = new HashMap<>();
    private static final Map<String, Profile> SP = new HashMap<>();

    static {
        SM.put("production", "prod");
        SM.put("prod", "prod");

        SM.put("preonline", "pre");
        SM.put("pre", "pre");

        SM.put("beta", "beta");
        SM.put("test", "test");
        SM.put("development", "dev");
        SM.put("dev", "dev");
        SM.put("default", "default");
    }


    public static final Profile PROD = new Profile("prod");

    public static final Profile PRE = new Profile("pre");

    public static final Profile BETA = new Profile("beta");

    public static final Profile TEST = new Profile("test");

    public static final Profile DEV = new Profile("dev");

    public static final Profile DEFAULT = new Profile("default");

    static {
        SP.put("prod", PROD);
        SP.put("pre", PRE);
        SP.put("beta", BETA);
        SP.put("test", TEST);
        SP.put("dev", DEV);
        SP.put("default", DEFAULT);
    }

    private String facade;//任意输入的字面值、形近字值
    private String standard;//规范值
    private String child;
    private String parent;

    public String getFacade() {
        return facade;
    }

    public String getStandard() {
        return standard;
    }

    public String getChild() {
        return child;
    }

    public String getParent() {
        return parent;
    }

    public boolean isStandard() {
        return this.standard != null;
    }

    private Profile(String facade) {
        this.facade = facade;
        String[] segments = facade.split(SEPARATOR);
        parent = segments.length >= 2 ? segments[1] : segments[0];
        child = segments.length >= 2 ? segments[0] : null;
        if (SM.containsKey(parent)) {
            this.standard = SM.get(parent);
        }
    }


    public static Profile profileOf(String profile) {
        if (profile == null) {
            return null;
        }
        String lc = profile.toLowerCase();
        String sn = SM.get(lc);
        if (sn != null) {
            return SP.get(sn);
        }
        return new Profile(lc);
    }

    public String prefer() {
        return isStandard() ? this.standard : this.facade;
    }

    public static Map<String, Profile> standards() {
        return Collections.unmodifiableMap(SP);
    }

    public static Profile standard(String profile) {
        if (profile == null) {
            return null;
        }
        String lc = profile.toLowerCase();
        String sn = SM.get(lc);
        return SP.get(sn);
    }

}
